package com.mixed.mixedserver.game.network;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mixed.mixedserver.game.entity.GameMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GameMessageEncoder extends MessageToByteEncoder<GameMessage> {
    private static final Logger logger = LoggerFactory.getLogger(GameMessageEncoder.class);
    private final ObjectMapper objectMapper;
    
    public GameMessageEncoder() {
        this.objectMapper = new ObjectMapper(new MessagePackFactory());
    }
    
    @Override
    protected void encode(ChannelHandlerContext ctx, GameMessage msg, ByteBuf out) throws Exception {
        try {
            // 序列化消息
            byte[] messageBytes = objectMapper.writeValueAsBytes(msg);
            
            // 写入消息长度（4字节）
            out.writeInt(messageBytes.length);
            
            // 写入消息数据
            out.writeBytes(messageBytes);
            
            logger.debug("Encoded message: type={}, playerId={}, size={} bytes", 
                msg.getType(), msg.getPlayerId(), messageBytes.length);
                
        } catch (Exception e) {
            logger.error("Failed to encode message: type={}, playerId={}", 
                msg.getType(), msg.getPlayerId(), e);
            throw e;
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("Encoder exception", cause);
        super.exceptionCaught(ctx, cause);
    }
}